package com.xmb.wechat.delegate;

import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.othershe.combinebitmap.CombineBitmap;
import com.othershe.combinebitmap.layout.WechatLayoutManager;
import com.xmb.wechat.R;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.baserecyclerview.BaseRecyclerViewManager;
import com.xmb.wechat.bean.GroupTalkBean;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.bean.WechatContactBean_;
import com.xmb.wechat.bean.WechatLastMsgBean;
import com.xmb.wechat.bean.WechatLastMsgBean_;
import com.xmb.wechat.common.Constant;
import com.xmb.wechat.util.SpanStringUtils;
import com.xmb.wechat.view.wechat.chat.WechatQunliaoDetailActivity;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import io.objectbox.Box;

/**
 * @Author lijiangop
 * @CreateTime 2020/4/30 14:09
 */
public class GroupTalkDelegate extends BaseRecyclerViewManager {

    private AssetManager           mManager;
    private Box<WechatLastMsgBean> mWechatLastMsgBeanBox;
    private Box<WechatContactBean> mWechatContactBeanBox;

    public GroupTalkDelegate(Activity activity, Box<WechatLastMsgBean> lastMsgBeanBox) {
        super(activity);
        mManager = context.getResources().getAssets();
        mWechatLastMsgBeanBox = lastMsgBeanBox;
        mWechatContactBeanBox = WechatStartApplication.getBoxStore().boxFor(WechatContactBean.class);
    }

    @Override
    public BaseQuickAdapter initAdapter() {
        return new BaseQuickAdapter<GroupTalkBean, BaseViewHolder>(R.layout.item_group_talk, new ArrayList<>()) {
            @Override
            protected void convert(BaseViewHolder helper, GroupTalkBean item) {
                ImageView imageView = helper.getView(R.id.iv_avatar);
                CombineBitmap.init(context).setLayoutManager(new WechatLayoutManager()) // 必选， 设置图片的组合形式，支持WechatLayoutManager、DingLayoutManager
                        .setSize(45) // 必选，组合后Bitmap的尺寸，单位dp
                        .setGap(1) // 单个图片之间的距离，单位dp，默认0dp
                        .setPlaceholder(R.drawable.ic_wx_default_avatar) // 单个图片加载失败的默认显示图片
                        .setBitmaps(getGroupAvatars(item.getGroupMembersList()))
                        .setImageView(imageView) // 直接设置要显示图片的ImageView
                        .build();
                helper.setText(R.id.name, TextUtils.isEmpty(item.getGroupName()) ? "" : item.getGroupName());

                helper.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WechatQunliaoDetailActivity.start(context, item);
                    }
                });

                if (mWechatLastMsgBeanBox == null)
                    return;
                WechatLastMsgBean latestMsg = mWechatLastMsgBeanBox.query().equal(WechatLastMsgBean_.isRoomChat, true)
                        .equal(WechatLastMsgBean_.talkerID, item.getId()).build().findUnique();
                if (latestMsg != null) {
                    Log.e("sana", "还有数据2？" + latestMsg.toString());
                    if (!TextUtils.isEmpty(latestMsg.getMsgContent()))
                        helper.setText(R.id.content, SpanStringUtils.getOnlyEmotion(mContext, helper.getView(R.id.content),
                                getMsgContent(latestMsg.getSenderID(), latestMsg.getMsgContent())));
                    helper.setText(R.id.time, TimeUtils.date2String(latestMsg.getTime(), new SimpleDateFormat("HH:mm")));
                } else {
                    helper.setText(R.id.content, "");
                }
            }
        };
    }

    private String getMsgContent(long senderID, String msgContent) {
        msgContent = TextUtils.isEmpty(msgContent) ? "" : msgContent;
        if (mWechatContactBeanBox == null || senderID == 0 || senderID == -1)
            return msgContent;
        else {
            WechatContactBean unique = mWechatContactBeanBox.query().equal(WechatContactBean_.id, senderID).build().findUnique();
            return unique == null ? msgContent : TextUtils.isEmpty(unique.getName()) ? msgContent : unique.getName() + ": " + msgContent;
        }
    }

    /**
     * 获取群聊信息的头像
     *
     * @param groupMemberList
     * @return
     */
    public Bitmap[] getGroupAvatars(List<WechatContactBean> groupMemberList) {
        if (groupMemberList == null)
            return new Bitmap[]{};
        if (groupMemberList.size() == 0)
            return new Bitmap[]{};
        //排序
        ArrayList<WechatContactBean> wechatContactBeans = new ArrayList<>(groupMemberList);
        Collections.sort(wechatContactBeans, new Comparator<WechatContactBean>() {
            @Override
            public int compare(WechatContactBean o1, WechatContactBean o2) {
                return o1.getGroupSort() - o2.getGroupSort();
            }
        });
        //获取9宫格图
        Bitmap[] bitmaps = new Bitmap[Math.min(wechatContactBeans.size(), 9)];//该框架超过9图会报bug
        for (int i = 0; i < bitmaps.length; i++) {
            WechatContactBean wechatContactBean = wechatContactBeans.get(i);
            if (wechatContactBean == null) {
                bitmaps[i] = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wx_default_avatar);
                continue;
            }
            if (wechatContactBean.getAvatarSrc() == Constant.SourceType.AVATAR_SRC_SDCARD) {
                try {
                    bitmaps[i] = loadBitmap(wechatContactBean.getAvatar());
                } catch (FileNotFoundException e) {
                    bitmaps[i] = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wx_default_avatar);
                    e.printStackTrace();
                }
            } else if (wechatContactBean.getAvatarSrc() == Constant.SourceType.AVATAR_SRC_APP_INNER_ASSETS) {
                try {
                    Bitmap bitmap = mManager == null ? BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wx_default_avatar) :
                            BitmapFactory.decodeStream(mManager.open("avatars/" + wechatContactBean.getAvatar()));
                    bitmaps[i] = bitmap == null ? BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wx_default_avatar) : bitmap;
                } catch (Exception e) {
                    bitmaps[i] = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wx_default_avatar);
                    e.printStackTrace();
                }
            }
        }
        return bitmaps;
    }

    public static Bitmap loadBitmap(String picturePath) throws FileNotFoundException {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = true;
        // 获取到这个图片的原始宽度和高度
        int picWidth = opt.outWidth;
        int picHeight = opt.outHeight;
        // 获取画布中间方框的宽度和高度
        int screenWidth = SizeUtils.dp2px(45);
        // isSampleSize是表示对图片的缩放程度，比如值为2图片的宽度和高度都变为以前的1/2
        opt.inSampleSize = 1;
        // 根据屏的大小和图片大小计算出缩放比例
        if (picWidth > picHeight) {
            if (picWidth > screenWidth)
                opt.inSampleSize = picWidth / screenWidth;
        } else {
            if (picHeight > screenWidth)
                opt.inSampleSize = picHeight / screenWidth;
        }
        // 生成有像素经过缩放了的bitmap
        opt.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(picturePath, opt);
        if (bitmap == null) {
            throw new FileNotFoundException("Couldn't open " + picturePath);
        }
        return bitmap;
    }
}
